package com.avcompris.util;

import static com.avcompris.util.ExceptionUtils.nonNullArgument;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import com.avcompris.common.annotation.Nullable;

/**
 * Utilities for test properties that, for instance, enable to load a property
 * files if it exists without crashing if it does not.
 * 
 * @author David Andrianavalontsalama
 */
public abstract class TestPropertiesUtils extends AbstractUtils {

	/**
	 * Load a "test.properties" file if it exists in the current
	 * {@link ClassLoader}.
	 */
	@Nullable
	public static Properties loadTestPropertiesIfAny() {

		return loadPropertiesIfAny("test.properties");
	}

	/**
	 * Load a property file if it exists in the current {@link ClassLoader}.
	 */
	@Nullable
	public static Properties loadPropertiesIfAny(final String filename) {

		nonNullArgument(filename, "filename");

		final ClassLoader classLoader = Thread.currentThread()
				.getContextClassLoader();

		final InputStream is = classLoader.getResourceAsStream(filename);

		if (is == null) {
			return null;
		}

		try {

			try {

				return PropertiesUtils.getProcessedProperties(is);

			} finally {
				is.close();
			}

		} catch (final IOException e) {
			throw new RuntimeException(e);
		}
	}
}
